<?php


namespace EchoPHP\Foundation\BootStrap;


use EchoPHP\Config\Config;
use EchoPHP\Foundation\Application;
use Symfony\Component\Finder\Finder;

/**
 * 项目配置文件加载
 * Class LoadConfiguration
 * @package EchoPHP\Foundation\BootStrap
 */
class LoadConfiguration {

    protected $appEnv;

    public function bootstrap(Application $app) {
        $configItem = [];
        $config = new Config($configItem);
        $app->instance('config', $config);

        $this->appEnv = env('APP_ENV', 'product');
        if (!in_array($this->appEnv, ['develop', 'test', 'product'], true)) {
            die('APP_ENV 定义错误');
        }
        $this->loadConstants($app);
        $this->loadConfigurationFiles($app, $config);

        date_default_timezone_set($config->get('app.timezone', 'Asia/Shanghai'));
        mb_internal_encoding('UTF-8');
    }

    /**
     * 加载配置文件
     * @param Application $app
     * @param $config Config
     * @throws \Exception
     */
    protected function loadConfigurationFiles(Application $app, $config) {
        $files = $this->getConfigurationFiles($app);
        foreach ($files as $key => $path) {
            $config->set($key, require $path);
        }

        $moduleFiles = $this->getModuleConfigurationFiles($app);
        foreach ($moduleFiles as $key => $path) {
            $config->set($key, require $path, false);
        }
    }

    /**
     * 获取配置文件
     * @param Application $app
     * @return array
     * @throws \Exception
     */
    protected function getConfigurationFiles(Application $app) {
        $files = [];
        $configPath = realpath($app->make('path.config') . '/' . $this->appEnv);
        foreach (Finder::create()->files()->name('*.php')->notName('constant.php')->in($configPath)->depth(0) as $file) {
            $files[basename($file->getRealPath(), '.php')] = $file->getRealPath();
        }

        ksort($files, SORT_NATURAL);

        return $files;
    }

    /**
     * 获取模块下配置文件
     * @param Application $app
     * @return array
     * @throws \Exception
     */
    protected function getModuleConfigurationFiles(Application $app) {
        $files = [];
        $configPath = realpath($app->make('path.config')) . '/' . $this->appEnv . '/' . MODULE_NAME;
        if (!is_dir($configPath)) {
            return $files;
        }
        foreach (Finder::create()->files()->name('*.php')->in($configPath)->depth(0) as $file) {
            $files[basename($file->getRealPath(), '.php')] = $file->getRealPath();
        }

        ksort($files, SORT_NATURAL);

        return $files;
    }

    /**
     * 加载常量定义
     * @param Application $app
     * @throws \Exception
     */
    protected function loadConstants(Application $app) {
        $configPath = realpath($app->make('path.config') . '/' . $this->appEnv);
        $constantFile = $configPath . '/constant.php';
        if (is_file($constantFile)) {
            require_once $constantFile;
        }
    }

}